<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🚌 公交站查询系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .header h1 {
            color: #333;
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            color: #666;
            font-size: 1.1em;
        }

        .tabs {
            display: flex;
            margin-bottom: 30px;
            border-bottom: 2px solid #f0f0f0;
        }

        .tab {
            flex: 1;
            padding: 15px;
            text-align: center;
            cursor: pointer;
            background: none;
            border: none;
            font-size: 16px;
            color: #666;
            transition: all 0.3s ease;
        }

        .tab.active {
            color: #667eea;
            border-bottom: 3px solid #667eea;
        }

        .tab-content {
            display: none;
            animation: fadeIn 0.5s ease-in;
        }

        .tab-content.active {
            display: block;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .upload-area {
            border: 3px dashed #667eea;
            border-radius: 15px;
            padding: 40px;
            text-align: center;
            margin-bottom: 20px;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .upload-area:hover {
            border-color: #764ba2;
            background: #f8f9ff;
        }

        .upload-area.dragover {
            border-color: #52c41a;
            background: #f6ffed;
        }

        .upload-icon {
            font-size: 48px;
            color: #667eea;
            margin-bottom: 15px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }

        .form-group input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 30px;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            margin-top: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .results {
            display: none;
            margin-top: 30px;
        }

        .location-info {
            background: #e6f7ff;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .station-card {
            background: #f9f9f9;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            border-left: 4px solid #667eea;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }

        .station-card:hover {
            background: #e6f7ff;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .station-card.selected {
            background: #e6f7ff;
            border-left-color: #52c41a;
            box-shadow: 0 5px 15px rgba(82, 196, 26, 0.2);
        }

        .select-station-btn {
            background: #52c41a;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 15px;
            font-size: 12px;
            cursor: pointer;
            position: absolute;
            top: 15px;
            right: 15px;
        }

        .select-station-btn:hover {
            background: #389e0d;
        }

        .route-section {
            display: none;
            margin-top: 30px;
            background: #f6ffed;
            border-radius: 15px;
            padding: 25px;
            border: 2px solid #52c41a;
        }

        .route-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            border-left: 4px solid #52c41a;
        }

        .route-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .route-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }

        .route-info {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .route-info-item {
            background: #f0f9ff;
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 12px;
            color: #1890ff;
        }

        .route-steps {
            list-style: none;
            padding: 0;
        }

        .route-steps li {
            background: #fafafa;
            padding: 10px;
            margin-bottom: 8px;
            border-radius: 8px;
            border-left: 3px solid #52c41a;
            position: relative;
            padding-left: 25px;
        }

        .route-steps li:before {
            content: counter(step-counter);
            counter-increment: step-counter;
            position: absolute;
            left: 8px;
            top: 10px;
            background: #52c41a;
            color: white;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            font-weight: bold;
        }

        .route-steps {
            counter-reset: step-counter;
        }

        .station-name {
            font-size: 20px;
            font-weight: bold;
            color: #333;
            margin-bottom: 8px;
        }

        .station-distance {
            color: #52c41a;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .bus-lines {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 10px;
        }

        .bus-line {
            background: #52c41a;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }

        .error {
            background: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
        }

        .success {
            background: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
        }

        .api-info {
            background: #f0f2f5;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            text-align: center;
        }

        .api-info a {
            color: #667eea;
            text-decoration: none;
            font-weight: bold;
        }

        .api-info a:hover {
            text-decoration: underline;
        }

        @media (max-width: 600px) {
            .container {
                margin: 10px;
                padding: 20px;
            }

            .header h1 {
                font-size: 2em;
            }

            .tabs {
                flex-direction: column;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>🚌 公交站查询系统</h1>
            <p>上传图片或输入坐标，快速查找附近的公交站</p>
        </div>

        <div class="tabs">
            <button class="tab active" onclick="switchTab('upload')">📷 图片上传</button>
            <button class="tab" onclick="switchTab('location')">📍 坐标查询</button>
        </div>

        <!-- 图片上传标签页 -->
        <div id="upload" class="tab-content active">
            <div class="upload-area" id="uploadArea" onclick="document.getElementById('fileInput').click()">
                <div class="upload-icon">📁</div>
                <h3>点击或拖拽图片到这里</h3>
                <p>支持 JPG、PNG 格式，自动提取GPS信息</p>
                <input type="file" id="fileInput" accept="image/*" style="display: none;"
                    onchange="handleFileSelect(event)">
            </div>

            <div class="form-group">
                <label>备用纬度（可选）</label>
                <input type="number" id="fallbackLat" placeholder="例如: 31.2304" step="any">
            </div>

            <div class="form-group">
                <label>备用经度（可选）</label>
                <input type="number" id="fallbackLng" placeholder="例如: 121.4737" step="any">
            </div>

            <button class="btn" id="uploadBtn" onclick="uploadImage()" disabled>🚀 查找公交站</button>
        </div>

        <!-- 坐标查询标签页 -->
        <div id="location" class="tab-content">
            <div class="form-group">
                <label>纬度 *</label>
                <input type="number" id="latitude" placeholder="例如: 31.2304" step="any" required>
            </div>

            <div class="form-group">
                <label>经度 *</label>
                <input type="number" id="longitude" placeholder="例如: 121.4737" step="any" required>
            </div>

            <div class="form-group">
                <label>地址描述（可选）</label>
                <input type="text" id="address" placeholder="例如: 上海市黄浦区">
            </div>

            <button class="btn" onclick="searchByLocation()">🔍 查找公交站</button>
            <button class="btn" onclick="getCurrentLocation()" style="background: #52c41a; margin-top: 10px;">📍
                获取当前位置</button>
        </div>

        <!-- 加载动画 -->
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>正在查询附近的公交站...</p>
        </div>

        <!-- 结果显示 -->
        <div class="results" id="results"></div>

        <!-- API信息 -->
        <div class="api-info">
            <p>🔗 API文档: <a href="http://localhost:8080/docs" target="_blank">http://localhost:8080/docs</a></p>
            <p>⚙️ 服务状态: <span id="apiStatus">检查中...</span></p>
        </div>
    </div>

    <script>
        let selectedFile = null;

        // 检查API状态
        async function checkApiStatus() {
            try {
                const response = await fetch('http://localhost:8080/api/bus-station/test');
                const data = await response.json();
                document.getElementById('apiStatus').innerHTML = '✅ 正常运行';
                document.getElementById('apiStatus').style.color = '#52c41a';
            } catch (error) {
                document.getElementById('apiStatus').innerHTML = '❌ 连接失败';
                document.getElementById('apiStatus').style.color = '#ff4d4f';
            }
        }

        // 切换标签页
        function switchTab(tabName) {
            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });

            // 移除所有标签的激活状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });

            // 显示选中的标签内容
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');

            // 清除结果
            hideResults();
        }

        // 处理文件选择
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (file) {
                selectedFile = file;
                document.getElementById('uploadBtn').disabled = false;

                // 更新上传区域显示
                const uploadArea = document.getElementById('uploadArea');
                uploadArea.innerHTML = `
                    <div class="upload-icon">✅</div>
                    <h3>已选择: ${file.name}</h3>
                    <p>文件大小: ${(file.size / 1024 / 1024).toFixed(2)} MB</p>
                `;
            }
        }

        // 拖拽上传
        const uploadArea = document.getElementById('uploadArea');

        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');

            const files = e.dataTransfer.files;
            if (files.length > 0) {
                const file = files[0];
                if (file.type.startsWith('image/')) {
                    selectedFile = file;
                    document.getElementById('uploadBtn').disabled = false;

                    uploadArea.innerHTML = `
                        <div class="upload-icon">✅</div>
                        <h3>已选择: ${file.name}</h3>
                        <p>文件大小: ${(file.size / 1024 / 1024).toFixed(2)} MB</p>
                    `;
                } else {
                    showError('请选择图片文件');
                }
            }
        });

        // 上传图片并查询
        async function uploadImage() {
            if (!selectedFile) {
                showError('请先选择图片文件');
                return;
            }

            showLoading();

            const formData = new FormData();
            formData.append('file', selectedFile);

            const fallbackLat = document.getElementById('fallbackLat').value;
            const fallbackLng = document.getElementById('fallbackLng').value;

            if (fallbackLat) formData.append('fallback_lat', fallbackLat);
            if (fallbackLng) formData.append('fallback_lng', fallbackLng);

            try {
                const response = await fetch('http://localhost:8080/api/bus-station/upload-image', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                hideLoading();

                if (data.status === 'success') {
                    showResults(data);
                } else {
                    showError(data.message || '查询失败');
                }
            } catch (error) {
                hideLoading();
                showError('网络错误: ' + error.message);
            }
        }

        // 根据坐标查询
        async function searchByLocation() {
            const latitude = document.getElementById('latitude').value;
            const longitude = document.getElementById('longitude').value;
            const address = document.getElementById('address').value;

            if (!latitude || !longitude) {
                showError('请输入有效的经纬度');
                return;
            }

            showLoading();

            const requestData = {
                latitude: parseFloat(latitude),
                longitude: parseFloat(longitude),
                address: address || '用户指定位置'
            };

            try {
                const response = await fetch('http://localhost:8080/api/bus-station/by-location', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                const data = await response.json();
                hideLoading();

                if (data.status === 'success') {
                    showResults(data);
                } else {
                    showError(data.message || '查询失败');
                }
            } catch (error) {
                hideLoading();
                showError('网络错误: ' + error.message);
            }
        }

        // 获取当前位置
        function getCurrentLocation() {
            if (!navigator.geolocation) {
                showError('您的浏览器不支持地理定位');
                return;
            }

            navigator.geolocation.getCurrentPosition(
                (position) => {
                    document.getElementById('latitude').value = position.coords.latitude.toFixed(6);
                    document.getElementById('longitude').value = position.coords.longitude.toFixed(6);
                    showSuccess('位置获取成功！');
                },
                (error) => {
                    showError('位置获取失败: ' + error.message);
                }
            );
        }

        // 显示加载动画
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            hideResults();
        }

        // 隐藏加载动画
        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }

        // 显示结果
        function showResults(data) {
            const resultsDiv = document.getElementById('results');
            const location = data.current_location;
            const stations = data.nearby_stations;

            let html = `
                <h3>📍 查询结果</h3>
                <div class="location-info">
                    <h4>当前位置</h4>
                    <p><strong>地址:</strong> ${location.address || '未知位置'}</p>
                    <p><strong>坐标:</strong> ${location.latitude.toFixed(6)}, ${location.longitude.toFixed(6)}</p>
                </div>
                
                <h4>🚌 附近公交站 (${stations.length}个) - 点击选择站点</h4>
            `;

            if (stations.length === 0) {
                html += '<p>未找到附近的公交站</p>';
            } else {
                stations.forEach((station, index) => {
                    html += `
                        <div class="station-card" onclick="selectStation(${index})">
                            <button class="select-station-btn" onclick="event.stopPropagation(); selectStation(${index})">选择此站</button>
                            <div class="station-name">${station.station_name}</div>
                            <div class="station-distance">📏 距离: ${station.distance}米</div>
                            <div class="bus-lines">
                                ${station.bus_lines.map(line => `<span class="bus-line">${line}</span>`).join('')}
                            </div>
                            <p><strong>地址:</strong> ${station.address}</p>
                            <p><strong>坐标:</strong> ${station.latitude.toFixed(6)}, ${station.longitude.toFixed(6)}</p>
                        </div>
                    `;
                });
            }

            // 添加路线规划区域
            html += `
                <div class="route-section" id="routeSection">
                    <h3>🗺️ 路线规划</h3>
                    <div id="selectedStationInfo"></div>
                    <button class="btn" onclick="planRoute()" id="planRouteBtn">🚀 开始规划路线</button>
                    <div id="routeResults"></div>
                </div>
            `;

            resultsDiv.innerHTML = html;
            resultsDiv.style.display = 'block';

            // 存储查询结果数据
            window.searchResults = data;
        }

        let selectedStationIndex = -1;

        // 选择公交站
        function selectStation(index) {
            // 移除之前的选中状态
            document.querySelectorAll('.station-card').forEach(card => {
                card.classList.remove('selected');
            });

            // 添加新的选中状态
            const cards = document.querySelectorAll('.station-card');
            if (cards[index]) {
                cards[index].classList.add('selected');
            }

            selectedStationIndex = index;
            const station = window.searchResults.nearby_stations[index];

            // 显示路线规划区域
            const routeSection = document.getElementById('routeSection');
            routeSection.style.display = 'block';

            // 更新选中站点信息
            const selectedStationInfo = document.getElementById('selectedStationInfo');
            selectedStationInfo.innerHTML = `
                <div class="location-info" style="background: #e6f7ff;">
                    <h4>🎯 已选择目标站点</h4>
                    <p><strong>站点名称:</strong> ${station.station_name}</p>
                    <p><strong>距离:</strong> ${station.distance}米</p>
                    <p><strong>经过线路:</strong> ${station.bus_lines.join(', ')}</p>
                </div>
            `;

            showSuccess(`已选择公交站: ${station.station_name}`);
        }

        // 规划路线
        async function planRoute() {
            if (selectedStationIndex === -1) {
                showError('请先选择一个公交站');
                return;
            }

            const station = window.searchResults.nearby_stations[selectedStationIndex];
            const currentLocation = window.searchResults.current_location;

            showLoading();

            const routeRequest = {
                destination_station: station.station_name,
                destination_lat: station.latitude,
                destination_lng: station.longitude,
                origin_lat: currentLocation.latitude,
                origin_lng: currentLocation.longitude,
                origin_address: currentLocation.address || '当前位置'
            };

            try {
                const response = await fetch('http://localhost:8080/api/bus-station/route-plan', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(routeRequest)
                });

                const data = await response.json();
                hideLoading();

                if (data.status === 'success') {
                    showRouteResults(data.routes);
                } else {
                    showError(data.message || '路线规划失败');
                }
            } catch (error) {
                hideLoading();
                showError('网络错误: ' + error.message);
            }
        }

        // 显示路线规划结果
        function showRouteResults(routes) {
            const routeResults = document.getElementById('routeResults');

            let html = `<h4>🚀 推荐路线方案 (${routes.length}个)</h4>`;

            routes.forEach((route, index) => {
                html += `
                    <div class="route-card">
                        <div class="route-header">
                            <div class="route-title">方案 ${index + 1}: ${route.route_description}</div>
                        </div>
                        <div class="route-info">
                            <div class="route-info-item">📏 ${route.total_distance}</div>
                            <div class="route-info-item">⏱️ ${route.estimated_time}</div>
                            <div class="route-info-item">🔄 换乘${route.transfer_count}次</div>
                        </div>
                        <h5>📋 详细步骤:</h5>
                        <ol class="route-steps">
                            ${route.steps.map(step => `<li>${step}</li>`).join('')}
                        </ol>
                    </div>
                `;
            });

            routeResults.innerHTML = html;
            showSuccess(`成功规划 ${routes.length} 条路线！`);
        }

        // 隐藏结果
        function hideResults() {
            document.getElementById('results').style.display = 'none';
            // 清除错误和成功消息
            const existingMessages = document.querySelectorAll('.error, .success');
            existingMessages.forEach(msg => msg.remove());
        }

        // 显示错误信息
        function showError(message) {
            hideResults();
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error';
            errorDiv.innerHTML = '❌ ' + message;
            document.querySelector('.container').appendChild(errorDiv);

            setTimeout(() => errorDiv.remove(), 5000);
        }

        // 显示成功信息
        function showSuccess(message) {
            const successDiv = document.createElement('div');
            successDiv.className = 'success';
            successDiv.innerHTML = '✅ ' + message;
            document.querySelector('.container').appendChild(successDiv);

            setTimeout(() => successDiv.remove(), 3000);
        }

        // 页面加载完成后检查API状态
        window.addEventListener('load', checkApiStatus);
    </script>
</body>

</html>